import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class HttpHelperService {

  constructor(private http: HttpClient) { }

  /* get请求 */
  public get(url: string): Observable<any> {
    return this.http.get<any>(url, httpOptions).pipe(
      tap((obj: any) => console.debug(obj)),
      catchError(this.handleError<any>("get"))
    );
  }

  /* post请求 */
  public post(url: string, body: any): Observable<any> {
    return this.http.post<any>(url, body, httpOptions).pipe(
      tap((obj: any) => console.debug(obj)),
      catchError(this.handleError<any>("post"))
    );
  }

  /* put请求 */
  public put(url: string, body: any): Observable<any> {
    return this.http.put<any>(url, body, httpOptions).pipe(
      tap((obj: any) => console.debug(obj)),
      catchError(this.handleError<any>("put"))
    );
  }

  /* delete请求 */
  public delete(url: string): Observable<any> {
    return this.http.delete<any>(url, httpOptions).pipe(
      tap((obj: any) => console.debug(obj)),
      catchError(this.handleError<any>("put"))
    );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {

      // TODO: send the error to remote logging infrastructure
      console.error(error); // log to console instead

      // TODO: better job of transforming error for user consumption
      console.log(`${operation} failed: ${error.message}`);

      // Let the app keep running by returning an empty result.
      return of(result as T);
    };
  }
}
